/*
 * @Author: nainaiyi s15037075861@163.com
 * @Date: 2022-07-12 17:31:25
 * @LastEditors: nainaiyi s15037075861@163.com
 * @LastEditTime: 2022-09-05 15:58:05
 * @FilePath: \网站2001A尚盈盈7.12月考\demo\src\store\shop\shopReducer.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { fetch_add_data, ShopAction, fetch_count, fetch_isChecked, fetch_AllChecked } from "./shopAction"
export interface shopListType {
    id: string,
    url: string,
    price: number,
    title: string,
    desc: string,
    state: string,
    isChecked: boolean,
    count: number
}
export interface shopListState {
    shopList: shopListType[]
}
const initState: shopListState = {
    shopList: []
}

export const shopReducer = (state = initState, action: ShopAction) => {
    switch (action.type) {
        case fetch_add_data: {
            const item = state.shopList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++;
            } else {
                state.shopList = [...state.shopList, { ...action.payload, count: 1, isChecked: false }]
            }
            return {
                ...state,
                shopList: [...state.shopList]
            }
        }
        case fetch_count: {
            const item = state.shopList.find(item => item.id === action.id)
            if (item) {
                item.count = action.count
            }
            return {
                ...state,
                shopList: [...state.shopList]
            }
        }
        case fetch_isChecked: {
            const item = state.shopList.find(item => item.id === action.id)
            if (item) {
                item.isChecked = action.isChecked
            }
            return {
                ...state,
                shopList: [...state.shopList]
            }
        }
        case fetch_AllChecked: {
            console.log(action.payload)
            state.shopList.map(v => v.isChecked = action.payload)
            return {
                ...state,
                shopList: [...state.shopList]
            }
        }
        default:
            return state
    }
}